<template>
	<div>
		<u-upload :width="width" :accept="accept" :height="height" :fileList="fileList1" @afterRead="afterRead"
			@delete="deletePic" name="1" multiple :maxCount="maxCount">
			<view>
				<u-icon name="/static/index/upload.png" :size="width"></u-icon>
			</view>
		</u-upload>
	</div>
</template>

<script>
	import config from '@/common/config.js'
	export default {
		props: {
			width: {
				type: String,
				default: '130rpx'
			},
			height: {
				type: String,
				default: '130rpx'
			},
			maxCount: {
				type: Number,
				default: 10
			},
			accept: {
				type: String,
				default: 'image'
			}
		},
		data() {
			return {
				fileList1: [],
			}
		},
		methods: {
			setFileList(list) {
				this.fileList1 = list;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.urlArray();
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url
					}))
					fileListLen++
				}
				this.urlArray();
			},
			//格式化地址
			urlArray() {
				this.urllist = [];
				this.fileList1.map(res => {
					this.urllist.push(res.url)
				})
				this.$emit('getUrl', this.urllist);
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/web/file/upload.jhtml', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {},
						success: (res) => {
							let data = JSON.parse(res.data);
							resolve(data)
						}
					});
				})
			},
		}

	}
</script>

<style>
</style>